package com.cc.pms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cc.pms.service.ITeamApplicationService;
import com.cc.pms.service.ITeamMemberService;
import com.cc.pms.service.ITeamService;
import com.cc.common.core.domain.R;
import com.cc.common.core.page.PageQuery;
import com.cc.common.core.page.PageVo;
import com.cc.common.utils.DateUtils;
import com.cc.common.utils.SecurityUtils;
import com.cc.pms.domain.Team;
import com.cc.pms.domain.TeamApplication;
import com.cc.pms.domain.TeamMember;
import com.cc.pms.domain.vo.TeamApplicationVo;
import com.cc.pms.mapper.TeamApplicationMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 记录用户申请加入队伍的请求及处理状态 服务实现类
 * </p>
 *
 * @author corleone
 * @since 2025-04-19
 */
@Service
public class TeamApplicationServiceImpl extends ServiceImpl<TeamApplicationMapper, TeamApplication> implements ITeamApplicationService {


    @Resource
    private ITeamMemberService teamMemberService;

    @Resource
    private ITeamService iTeamService;

    @Override
    public R<Boolean> handleApplication(TeamApplication application) {
        TeamApplication teamApplication = getById(application.getId());
        if (teamApplication == null) {
            return R.fail(-1, "申请记录不存在");
        }

        Team team = iTeamService.getById(application.getTeamId());
        if (application.getStatus() == 1 && Objects.equals(team.getCurrentMembers(), team.getMaxMembers())){
            return R.fail(-1 , "队伍已满, 无法同意入队");
        }

        teamApplication.setHandlerId(SecurityUtils.getUserId());
        teamApplication.setStatus(application.getStatus());
        updateById(teamApplication);
        if (application.getStatus() == 1) {
            TeamMember member = new TeamMember();
            member.setTeamId(teamApplication.getTeamId());
            member.setUserId(teamApplication.getUserId());
            member.setIsCaptain(0);
            member.setJoinTime(DateUtils.getTime());
            teamMemberService.addMember(member);
        }
        return R.ok(true, "审批完成");
    }

    @Override
    public R<Long> applicationTeam(TeamApplication application) {
        if (application == null || application.getTeamId() == null) {
            return R.fail(-1, "请求数据不能为空");
        }
        Long userId = SecurityUtils.getUserId();
        application.setUserId(userId);
        TeamApplication teamApplication = queryTeamApplication(application.getTeamId(), userId);
        if (teamApplication == null) {
            application.setUserId(userId);
            application.setStatus(0);
            application.setApplyTime(DateUtils.getTime());
            return save(application) ? R.ok(application.getId()) : R.fail(-1, "申请入队失败");
        } else {
            teamApplication.setApplyTime(DateUtils.getTime());
            teamApplication.setStatus(0);
            teamApplication.setRemark(application.getRemark());
            return updateById(teamApplication) ? R.ok(application.getId()) : R.fail(-1, "申请入队失败");
        }
    }

    @Override
    public PageVo<TeamApplicationVo> queryMineApplicationTeamHistory(PageQuery query) {
        Page<TeamApplicationVo> page = new Page<>(query.getPageNum(), query.getPageSize());
        Page<TeamApplicationVo> teamApplicationVoPage = baseMapper.queryTeamApplicationHistory(page, SecurityUtils.getUserId());
        return PageVo.of(teamApplicationVoPage.getRecords(), teamApplicationVoPage.getTotal());
    }

    @Override
    public PageVo<TeamApplicationVo> queryManageApplicationTeamHistory(PageQuery query, Long teamId) {
        Page<TeamApplicationVo> page = new Page<>(query.getPageNum(), query.getPageSize());
        Page<TeamApplicationVo> teamApplicationVoPage = baseMapper.queryManageApplicationTeamHistory(page, teamId);
        return PageVo.of(teamApplicationVoPage.getRecords(), teamApplicationVoPage.getTotal());
    }

    @Override
    public void removeMemberApplication(Long teamId, List<Long> memberIds) {
        if (memberIds == null || memberIds.isEmpty()) {
            return;
        }
        LambdaUpdateWrapper<TeamApplication> lu = Wrappers.lambdaUpdate();
        lu.eq(TeamApplication::getTeamId, teamId);
        lu.in(TeamApplication::getUserId, memberIds);
        remove(lu);
    }

    @Override
    public void removeApplying(Long teamId) {
        LambdaUpdateWrapper<TeamApplication> luq = Wrappers.lambdaUpdate();
        luq.eq(TeamApplication::getTeamId ,teamId);
        luq.eq(TeamApplication::getStatus , 0);
        remove(luq);
    }

    @Override
    public void removeByTeamId(Long teamId) {
        lambdaUpdate().eq(TeamApplication::getTeamId , teamId).remove();
    }


    private TeamApplication queryTeamApplication(Long teamId, Long userId) {
        LambdaQueryWrapper<TeamApplication> lqw = Wrappers.lambdaQuery();
        lqw.eq(TeamApplication::getTeamId, teamId);
        lqw.eq(TeamApplication::getUserId, userId);
        lqw.last(" limit 1");
        return baseMapper.selectOne(lqw);
    }
}
